/*
 * Copyright (C) 2006-2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.IO;
using System.Security.Cryptography;
using System.Threading;

namespace DCSharp.Hashing
{
	public class HasherManaged : Hasher
	{
		private const int MaxLevels = 10;
		private const int MinBlockSize = 64 * 1024;

		private HashAlgorithm algorithm;
		private long bytesRemaining;

		public HasherManaged(HashAlgorithm algorithm)
		{
			this.algorithm = algorithm;
		}

		#region Properties

		public override long BytesRemaining
		{
			get { return bytesRemaining; }
		}

		#endregion

		#region Methods

		public override HashTree Hash(FileInfo fileInfo,
			ManualResetEvent abortHashingEvent)
		{
			try
			{
				return CreateHashTree(fileInfo, abortHashingEvent);
			}
			catch
			{
				bytesRemaining = 0;
				throw;
			}
		}

		private HashTree CreateHashTree(FileInfo fileInfo,
			ManualResetEvent abortHashingEvent)
		{
			long blockSize = HashTree.CalculateBlockSize(fileInfo.Length,
				MaxLevels);
			blockSize = Math.Max(blockSize, MinBlockSize);

			HashTree hashTree = new HashTree(algorithm, blockSize);

			using (FileStream stream = fileInfo.OpenRead())
			{
				bytesRemaining = stream.Length;

				int count;
				byte[] buffer = new byte[HashTree.SegmentSize * 8];
				do
				{
					count = stream.Read(buffer, 0, buffer.Length);
					if (count != 0)
					{
						hashTree.Update(buffer, 0, count);
						bytesRemaining -= count;
					}
				}
				while (count != 0 && !abortHashingEvent.WaitOne(0, false));
			}

			// The hashing was aborted
			if (bytesRemaining > 0 || abortHashingEvent.WaitOne(0, false))
			{
				bytesRemaining = 0;
				return null;
			}

			hashTree.CalculateRoot();
			return hashTree;
		}

		#endregion
	}
}
